package cn.bandeqing.shortMessage.service.impl;

import cn.bandeqing.customer.req.BindPhoneReq;
import cn.bandeqing.frame.exception.CodeException;
import cn.bandeqing.shortMessage.entity.ShortMessage;
import cn.bandeqing.shortMessage.mapper.ShortMessageMapper;
import cn.bandeqing.shortMessage.service.IShortMessageService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.lang.Assert;
import org.springframework.stereotype.Service;

import static cn.bandeqing.shortMessage.entity.table.ShortMessageTableDef.SHORT_MESSAGE;

/**
 * 短信 服务层实现。
 *
 * @author fugui
 * @since 2023-11-24
 */
@Service
public class ShortMessageServiceImpl extends ServiceImpl<ShortMessageMapper, ShortMessage> implements IShortMessageService {

    @Override
    public void checkTimes(String phone) {
        long count = count(QueryWrapper.create()
                .where(SHORT_MESSAGE.SM_PHONE.eq(phone))
                .where(SHORT_MESSAGE.CREATE_TIME.ge(DateUtil.offsetHour(DateUtil.now(), -1))));
        Assert.isTrue(count < 11, () -> new CodeException("验证码发送过于频繁，请稍后再试"));
    }

    @Override
    public void checkCode(BindPhoneReq req) {
        ShortMessage shortMessage = getOne(QueryWrapper.create()
                .select(SHORT_MESSAGE.SM_ID)
                .where(SHORT_MESSAGE.SM_PHONE.eq(req.getPhone()))
                .where(SHORT_MESSAGE.SM_CODE.eq(req.getCode()))
                .where(SHORT_MESSAGE.SM_CHECK.eq(false))
                .orderBy(SHORT_MESSAGE.SM_ID.desc())
                .limit(1));

        Assert.notNull(shortMessage, () -> new CodeException("验证码错误"));

        Assert.isTrue(updateById(ShortMessage.builder()
                .smId(shortMessage.getSmId())
                .smCheck(true)
                .build()), () -> new CodeException("验证码校验失败"));

    }

}
